<template>
  <pro-table
    ref="table"
    title="兑换列表"
    :request="getList"
    :columns="columns"
    :search="searchConfig"
    :pagination="paginationConfig"
    @selectionChange="handleSelectionChange"
  >
    <!-- 工具栏 -->
    <template #toolbar>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >
        添加
      </el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="refresh">
        刷新
      </el-button>
    </template>
    <template #operate="scope">
      <el-button
        size="mini"
        type="primary"
        @click="edit(scope.row)"
      >
        Edit
      </el-button>
      <el-popconfirm title="Are you sure to delete this?" @confirm="delCommodity(scope.row.id)">
        <template #reference>
          <el-button size="mini" type="danger">Delete</el-button>
        </template>
      </el-popconfirm>
    </template>
  </pro-table>


  <el-dialog
    v-model="addVisible"
    title="新增/编辑商品"
    width="380px"
  >
    <!--    表单-->
    <el-form
      ref="ruleFormRef"
      :model="addCommodity.item"
      :rules="addCommodity.rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="addCommodity.item.name"></el-input>
      </el-form-item>
      <el-form-item label="商品余量" prop="residue">
        <el-input-number v-model="addCommodity.item.residue" :min="1" />
      </el-form-item>
      <el-form-item label="兑换积分" prop="scale">
        <el-input-number v-model="addCommodity.item.scale" :min="1" />
      </el-form-item>
      <el-form-item label="每月限购" prop="limit">
        <el-input-number v-model="addCommodity.item.limit" :min="0" />
        <br>
        <small>为0不限制</small>
      </el-form-item>
      <el-form-item label="是否上架" prop="status">
        <el-radio-group v-model="addCommodity.item.status" size="large">
          <el-radio-button label="上架"></el-radio-button>
          <el-radio-button label="下架"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-radio-group v-model="addCommodity.item.type" size="large">
          <el-radio-button label="常规商品"></el-radio-button>
<!--          <el-radio-button label="CDK商品"></el-radio-button>-->
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm('ruleFormRef')">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, reactive, ref, toRefs } from "vue";
import { addCommodity, delCommodity, getCommodityList } from "../../api/commodity";
import { ElMessage } from "element-plus";


export default defineComponent({
  name: 'Commodity',
  setup() {
    const state = reactive({
      addCommodity: {
        item: {
          name: '',
          scale: 1,
          residue: 1,
          limit: 0,
          status: '上架',
          type: 'CDK商品',
        },
        rules: {
          name: [
            {
              required: true,
              message: '请输入商品名称',
              trigger: 'blur',
            },
          ],
          residue: [
            {
              required: true,
              message: '请输入剩余数量',
              trigger: 'blur',
            },
          ],
          scale: [
            {
              required: true,
              message: '请输入兑换积分',
              trigger: 'blur',
            },
          ],
          status: [
            {
              required: true,
              message: '请选择是否上架',
              trigger: 'change',
            },
          ],
          type: [
            {
              required: true,
              message: '请选择商品类型',
              trigger: 'change',
            },
          ],
        },
      },
      ruleFormRef: ref(),
      addVisible: ref(false),
      // 表格列配置，大部分属性跟el-table-column配置一样
      columns: [
        { type: 'selection' },
        { label: '序号', prop: 'id' },
        { label: '资源名称', prop: 'name', sortable: true, width: 180 },
        { label: '单位', prop: 'count' },
        { label: '积分', prop: 'scale' },
        {
          label: '操作',
          fixed: 'right',
          width: 180,
          align: 'center',
          tdSlot: 'operate', // 自定义单元格内容的插槽名称
        },
      ],
      // 搜索配置
      searchConfig: {
        labelWidth: '90px', // 必须带上单位
        inputWidth: '360px', // 必须带上单位
        fields: [
          {
            type: 'text',
            label: '资源名称',
            name: 'name',
          },
        ],
      },
      // 分页配置
      paginationConfig: {
        layout: 'total, prev, pager, next, sizes', // 分页组件显示哪些功能
        pageSize: 5, // 每页条数
        pageSizes: [5, 10, 20, 50],
        style: { textAlign: 'left' },
      },
      selectedItems: [],
      batchDelete() {
        console.log(state.selectedItems)
      },
      // 选择
      handleSelectionChange(arr) {
        state.selectedItems = arr
      },
      // 请求函数
      async getList(params) {
        // params是从组件接收的，包含分页和搜索字段。
        const { data } = await getCommodityList(params)

        // 必须要返回一个对象，包含data数组和total总数
        return {
          data: data.list,
          total: +data.total,
        }
      },
    })
    const table = ref(null)
    const refresh = () => {
      table.value.refresh()
    }
    const methods = {
      async delCommodity(rid) {
        let resp = await delCommodity(rid)
        if (resp.code !== 200) {
          ElMessage({
            message: resp.message || '服务器错误！',
            type: 'error',
          })
        } else {
          table.value.refresh()
          ElMessage({
            message: resp.message || 'ok',
            type: 'success',
          })
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let resp = await addCommodity(state.addCommodity.item)
            if (resp.code !== 200) {
              ElMessage({
                message: resp.message || '服务器错误！',
                type: 'error',
              })
            } else {
              state.addVisible = false
              state.addCommodity.item = {
                name: '',
                scale: 1,
                residue: 1,
                limit: 0,
                status: '上架',
                type: 'CDK商品',
              }
              table.value.refresh()
              ElMessage({
                message: resp.message || 'ok',
                type: 'success',
              })
            }
          } else {
            return false
          }
        })
      },
      add() {
        state.addCommodity.item = {
          name: '',
          scale: 1,
          residue: 1,
          limit: 0,
          status: '上架',
          type: 'CDK商品',
        }
        state.addVisible = true
      },
      edit(data) {
        state.addVisible = true
        state.addCommodity.item = {
          id: data.id,
          name: data.name,
          scale: data.scale,
          residue: data.residue,
          limit: data.limit,
          status: data.status,
          type: data.type,
        }
        console.log(state.addCommodity.item)
      },
    }
    return { ...toRefs(state), refresh, table, ...methods }
  },
})
</script>
